using System;
using System.Linq;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using Widgetsphere.Autos.API.FacetedNavigation;
using HP.Datastore.Common;
using Widgetsphere.Autos.API;

namespace Widgetsphere.Autos.Websitev2.UserControls
{
    public partial class DimensionListControl : System.Web.UI.UserControl
    {
        #region Class Members

        private int _companyId;
        private string _companyName;
        private ListingResults _results = null;
        private Dictionary<string, string> _orderList = null;

        #endregion

        #region Page Events

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            lstItem.ItemDataBound += new DataListItemEventHandler(lstItem_ItemDataBound);

        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
        }

        #endregion

        public bool UseSeo
        {
            get
            {
                if (this.ViewState["UseSeo"] == null)
                    return true;
                return (bool)this.ViewState["UseSeo"];
            }
            set { this.ViewState["UseSeo"] = value; }
        }

        #region Methods

        public void Populate(IListingResults results, Dictionary<string, string> orderList)
        {
            _orderList = orderList;

            //Order the dimensions
            var dimensionList = new List<DimensionItem>();
            var arr = ConfigHelper.JobDimensionOrder.Split('|');
            foreach (var dname in arr)
            {
                var d = results.DimensionList.FirstOrDefault(x => x.Name == dname);
                if (d != null) dimensionList.Add(d);
            }

            //Tack on all the others that were not found in order list
            dimensionList.AddRange(results.DimensionList.Where(x => !dimensionList.Contains(x)).ToList());

            lstItem.DataSource = dimensionList;
            lstItem.DataBind();
        }

        public void Populate(ListingResults results, int companyId, string companyName, Dictionary<string, string> orderList)
        {
            _orderList = orderList;
            _results = results;
            _companyId = companyId;
            _companyName = companyName;
            lstItem.DataSource = results.DimensionList.OrderBy(x => x.Name);
            lstItem.DataBind();
        }

        #endregion

        #region Property Implementations

        #endregion

        #region Event Handlers

        private void lstItem_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            var dimensionItem = e.Item.DataItem as DimensionItem;

            const int HIDE_LIMIT = 8;

            var pnlHeader = (PlaceHolder)e.Item.FindControl("pnlHeader");
            var linkHeader = new Literal();
            var dimensionDIsplay = dimensionItem.GetCeleriqDisplayName(_orderList);
            //if (dimensionDIsplay == DimensionStore.Dimension_Company)
            //    dimensionDIsplay = ResourceHelper.GetText(JobPlatform.SiteLibrary.Common.SiteTextContants.EmployerObjectSingularProper);
            linkHeader.Text = dimensionDIsplay;
            pnlHeader.Controls.Add(linkHeader);
            var pnlInside = e.Item.FindControl("pnlInside") as Panel;
            if (linkHeader.Text == string.Empty)
            {
                this.Visible = false;
                return;
            }

            var hidePanel = new Panel();
            hidePanel.Style.Add("display", "none");

            var showMore = new Literal();

            //Create a template query for speed
            var templateQuery = new ListingQuery(this.Request.Url.PathAndQuery);

            const int MAX_TEXT = 23;
            var index = 0;
            foreach (var refinementItem in dimensionItem.RefinementList.OrderBy(x => x.MinValue).OrderBy(x => x.FieldValue).ToList())
            {
                var query = ((ICloneable)templateQuery).Clone() as ListingQuery;
                query.PageOffset = 1;

                var link = new HtmlAnchor();
                var rValue = refinementItem.FieldValue;
                if (refinementItem.MinValue != null)
                    rValue = Convert.ToInt32(refinementItem.FieldValue).ToString("###,###,###,##0") + " - " + refinementItem.MaxValue.Value.ToString("###,###,###,##0");
                var text = rValue;
                if (text.Length > MAX_TEXT)
                {
                    text = text.Substring(0, MAX_TEXT - 3) + "...";
                }
                text += " <span class=\"badge\">" + refinementItem.Count + "</span>";
                link.InnerHtml = text;

                if (!query.DimensionValueList.Contains(refinementItem.DVIdx))
                    query.DimensionValueList.Add(refinementItem.DVIdx);

                //if (dimensionItem.Name == DimensionStore.Dimension_Company)
                //{
                //    //Special handling for companies
                //    var companyName = refinementItem.FieldValue;
                //    var cache = CacheDomain.EmployerCache.FirstOrDefault(x => x.Company == companyName);
                //    if (cache == null) cache = CacheDomain.AddEmployerCacheByName(companyName);

                //    if (query.DimensionValueList.Count == 1)
                //        query.DimensionValueList.Remove(refinementItem.DVIdx);
                //    query.CompanyName = companyName;
                //    if (cache != null)
                //        query.CompanyId = cache.EmployerId;
                //    link.HRef = query.ToSeoString();
                //    link.Attributes.Add("rel", "nofollow");
                //}
                //else
                {
                    if (_companyId > 0 && !string.IsNullOrEmpty(_companyName))
                    {
                        //query.CompanyName = _companyName;
                        query.ListingId = _companyId;
                        link.HRef = query.ToString();
                    }
                    else if (this.UseSeo)
                    {
                        link.HRef = query.ToString();
                    }
                    else
                    {
                        link.HRef = query.ToString();
                    }
                }

                link.Title = rValue + " (" + refinementItem.Count + " items)";
                //link.Attributes.Add("asynch-load", "");

                var breaker = new Label();
                breaker.Text = "<br />";

                var checkBox = new Literal();
                checkBox.Text = "<input type='checkbox' linktype='dlink' didx='" + dimensionItem.DIdx + "' dvidx='" + refinementItem.DVIdx + "' />";

                if (index < HIDE_LIMIT)
                {
                    pnlInside.Controls.Add(checkBox);
                    pnlInside.Controls.Add(link);
                    pnlInside.Controls.Add(breaker);
                }
                else
                {
                    hidePanel.Controls.Add(checkBox);
                    hidePanel.Controls.Add(link);
                    hidePanel.Controls.Add(breaker);
                }

                if (index == HIDE_LIMIT)
                {
                    pnlInside.Controls.Add(hidePanel);
                    pnlInside.Controls.Add(showMore);
                }

                index++;

            }

            var multiSelectButton = new Literal();
            multiSelectButton.Text = "<div align='right'><input type='button' buttontype='multi-dimension-apply' class='btn btn-primary btn-mini' value='Apply' didx='" + dimensionItem.DIdx + "' /></div>";
            pnlInside.Controls.Add(multiSelectButton);

            showMore.Text = "<div align='right'><a title='Show all values' href='javascript:;' class=\"noautoscroll dimshowmore\" onclick=\"" + "javascript:showMore('" + hidePanel.ClientID + "', this)" + "\">show more</a></div>";

        }

        #endregion

    }
}